/* eslint-disable no-unused-vars */
import React, { useEffect } from "react";
import { Layout } from "antd";
import { Helmet } from "react-helmet";
import { observer } from "mobx-react";
import BlogSider from "./components/BlogSider";
import BlogList from "./components/BlogList";
import { useStores } from "../store/store";
import { MAX_COUNT, MAX_COMMENT_COUNT, BLOG_BACKGROUND_IMG } from "../lib/config";
import { BlogInfo } from "../store/blog";
import {
    getBlogList,
    getBlogLabels,
    getNewComments,
    getAuthorInfo,
} from "../lib/httpReq";
import clientAxiosInstance from "../request";
import serverAxiosInstance from "../../serverRender/request";

function Specific() {
    // eslint-disable-next-line no-shadow
    const { blogTotal, authorInfo, recentBlogs, getNewBlogList, getAuthorInfo } = useStores('blogList') as BlogInfo;

    useEffect(() => {
        window.sessionStorage.setItem('authorInfo', JSON.stringify(authorInfo));
        window.sessionStorage.setItem('recentBlogs', JSON.stringify(recentBlogs));
    }, []);

    useEffect(() => {
        // 后端可能请求出错，重新请求一遍
        if (Object.keys(authorInfo).length === 0) {
            getAuthorInfo(clientAxiosInstance);
        }
        if (recentBlogs.length === 0) {
            getNewBlogList(0, clientAxiosInstance);
        }
    }, []);

    return (
        <Layout id="layout-content">
            <Helmet>
                <title>多云转晴的个人博客首页 - web前端技术文章</title>
                <meta name="description" content="多云转晴的个人博客首页，web前端学习笔记" />
            </Helmet>
            <div
                className="bgImg-container"
                style={{ backgroundImage: `url(${BLOG_BACKGROUND_IMG})` }}
            />
            <BlogSider />
            <BlogList total={blogTotal} />
        </Layout>
    );
}

Specific.loadData = (store: { blogList: BlogInfo }) => Promise.all([
    getBlogList(0, MAX_COUNT, "", serverAxiosInstance),
    getBlogLabels(serverAxiosInstance),
    getNewComments(0, MAX_COMMENT_COUNT, serverAxiosInstance),
    getAuthorInfo(serverAxiosInstance),
]).then((res) => {
    store.blogList.setBlogInfo(res[0].data.data);
    store.blogList.setRecentBlogs(res[0].data.data.result);
    store.blogList.setTOTAL(res[0].data.data.total);
    store.blogList.setLabelList(res[1].data.data);
    store.blogList.setNewComments(res[2].data.data.result);
    store.blogList.setAuthorInfo(res[3].data.data);
}).catch();

export default observer(Specific);
